package com.kang.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.base.LoginDataBase;
import com.kang.entity.SysUser;
import com.kang.mapper.UserMapper;
import com.kang.service.UserService;

import com.kang.util.AESSimpleUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Map<String ,Object> selectUser(HttpServletRequest request) {
        try {
            //获取用户信息
//            Integer token = TokenToUserId.TokenToUserId(request.getHeader("token"));
            String userToken = stringRedisTemplate.opsForValue().get("login:token:" + request.getHeader("token"));
            LoginDataBase loginDataBase = JSONObject.parseObject(userToken, LoginDataBase.class);
            Map<String ,Object> map = new HashMap<>();
            assert loginDataBase != null;
            SysUser user = loginDataBase.getUser();
            user.setPassword(user.getPassword());
            map.put("user",user);
            return map;
        } catch (Exception exception) {
            log.error("token转换获取id异常",exception);
            return null;
        }
    }

    @Override
    public String selectUserHeadUrl(HttpServletRequest request) throws Exception {
        //获取用户信息
//        Integer token = TokenToUserId.TokenToUserId(request.getHeader("token"));
        String userToken = stringRedisTemplate.opsForValue().get("login:token:" + request.getHeader("token"));
        LoginDataBase loginDataBase = JSONObject.parseObject(userToken, LoginDataBase.class);
        assert loginDataBase != null;
        return loginDataBase.getUser().getHeadUrl();
    }

    @Override
    public boolean updateUserInformation(SysUser sysUser,HttpServletRequest request) {
        String token = request.getHeader("token");
        stringRedisTemplate.delete("login:token:" + token);
        LoginDataBase loginDataBase = new LoginDataBase();
        sysUser.setPassword(AESSimpleUtil.encrypt(sysUser.getPassword()));
        loginDataBase.setUser(sysUser);
        stringRedisTemplate.opsForValue().set("login:token:" + token, JSONObject.toJSONString(loginDataBase),30, TimeUnit.MINUTES);
//        sysUser.setPhone(AESSimpleUtil.encrypt(sysUser.getPhone()));
        userMapper.updateById(sysUser);
        return true;
    }
}

